/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.web.vo.Paging;
import co.yixiang.enums.CommonEnum;
import co.yixiang.enums.ProductEnum;
import co.yixiang.enums.RedisKeyEnum;
import co.yixiang.exception.ErrorRequestException;
import co.yixiang.modules.shop.entity.YxStoreCategory;
import co.yixiang.modules.shop.entity.YxStoreProduct;
import co.yixiang.modules.shop.entity.YxStoreProductAttrValue;
import co.yixiang.modules.shop.mapper.YxStoreProductAttrValueMapper;
import co.yixiang.modules.shop.mapper.YxStoreProductMapper;
import co.yixiang.modules.shop.mapping.YxStoreProductMap;
import co.yixiang.modules.shop.service.*;
import co.yixiang.modules.shop.web.dto.ProductDTO;
import co.yixiang.modules.shop.web.param.YxStoreProductQueryParam;
import co.yixiang.modules.shop.web.vo.YxStoreCategoryQueryVo;
import co.yixiang.modules.shop.web.vo.YxStoreProductAttrQueryVo;
import co.yixiang.modules.shop.web.vo.YxStoreProductQueryVo;
import co.yixiang.modules.shop.web.vo.YxSystemStoreQueryVo;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.utils.CateDTO;
import co.yixiang.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author hupeng
 * @since 2019-10-19
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@SuppressWarnings("unchecked")
public class YxStoreProductServiceImpl extends BaseServiceImpl<YxStoreProductMapper, YxStoreProduct> implements YxStoreProductService {

    @Autowired
    private YxStoreProductMapper yxStoreProductMapper;
    @Autowired
    private YxStoreProductAttrValueMapper storeProductAttrValueMapper;

    @Autowired
    private YxStoreProductAttrService storeProductAttrService;
    @Autowired
    private YxStoreProductRelationService relationService;
    @Autowired
    private YxStoreProductReplyService replyService;
    @Autowired
    private YxUserService userService;
    @Autowired
    private YxSystemStoreService systemStoreService;

    @Autowired
    private YxStoreProductMap storeProductMap;
    @Autowired
    private YxStoreCategoryService yxStoreCategoryService;



    /**
     * 增加库存 减少销量
     *
     * @param num
     * @param productId
     * @param unique
     */
    @Override
    public void incProductStock(int num, int productId, String unique) {
        if (StrUtil.isNotEmpty(unique)) {
            storeProductAttrService.incProductAttrStock(num, productId, unique);
            yxStoreProductMapper.decSales(num, productId);
        } else {
            yxStoreProductMapper.incStockDecSales(num, productId);
        }
    }

    /**
     * 库存与销量
     *
     * @param num
     * @param productId
     * @param unique
     */
    @Override
    public void decProductStock(int num, int productId, String unique) {
        if (StrUtil.isNotEmpty(unique)) {
            storeProductAttrService.decProductAttrStock(num, productId, unique);
            yxStoreProductMapper.incSales(num, productId);
        } else {
            yxStoreProductMapper.decStockIncSales(num, productId);
        }
    }

    /**
     * 返回商品库存
     *
     * @param productId
     * @param unique
     * @return
     */
    @Override
    public int getProductStock(int productId, String unique) {
        if (StrUtil.isEmpty(unique)) {
            return getYxStoreProductById(productId).getStock();
        } else {
            return storeProductAttrService.uniqueByStock(unique);
        }

    }

    @Override
    public YxStoreProduct getProductInfo(int id) {
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0).eq("id", id);
        YxStoreProduct storeProduct = yxStoreProductMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(storeProduct)) {
            throw new ErrorRequestException("商品不存在或已下架");
        }

        return storeProduct;
    }

    @Override
    public ProductDTO goodsDetail(int id, int type, int uid, String latitude, String longitude) {
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0).eq("id", id);
        YxStoreProduct storeProduct = yxStoreProductMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(storeProduct)) {
            throw new ErrorRequestException("商品不存在或已下架");
        }
        Map<String, Object> returnMap = storeProductAttrService.getProductAttrDetail(id, 0, 0);
        ProductDTO productDTO = new ProductDTO();
        YxStoreProductQueryVo storeProductQueryVo = storeProductMap.toDto(storeProduct);

        //处理库存
        Integer newStock = storeProductAttrValueMapper.sumStock(id);
        if (newStock != null) storeProductQueryVo.setStock(newStock);


        storeProductQueryVo.setUserCollect(relationService
                .isProductRelation(id, "product", uid, "collect"));
        productDTO.setStoreInfo(storeProductQueryVo);
        List<YxStoreProductAttrQueryVo> attrList = (List<YxStoreProductAttrQueryVo>)returnMap.get("productAttr");
        productDTO.setProductAttr(attrList);
        productDTO.setProductValue( (Map<String, YxStoreProductAttrValue>)returnMap.get("productValue"));
        if(attrList != null && attrList.size() > 0){
            productDTO.setSuk(attrList.get(0).getAttrValues());
        }



        //门店
        productDTO.setSystemStore(systemStoreService.getStoreInfo(latitude, longitude));
        productDTO.setMapKey(RedisUtil.get(RedisKeyEnum.TENGXUN_MAP_KEY.getValue()));
        //其他门店信息
        QueryWrapper<YxStoreProduct> otherStoreProductWraper = new QueryWrapper<>();
        otherStoreProductWraper.eq("store_name", storeProductQueryVo.getStoreName()).ne("store_id", storeProductQueryVo.getStoreId());
        List<YxStoreProduct> otherStoreProductList = yxStoreProductMapper.selectList(otherStoreProductWraper);
        List<YxSystemStoreQueryVo> otherStoreList = new ArrayList<YxSystemStoreQueryVo>();
        for(YxStoreProduct yxStoreProduct : otherStoreProductList){
            YxSystemStoreQueryVo yxSystemStoreQueryVo = new YxSystemStoreQueryVo();
            yxSystemStoreQueryVo.setId(Integer.parseInt(yxStoreProduct.getStoreId()));
            yxSystemStoreQueryVo.setName(yxStoreProduct.getStorePname());
            yxSystemStoreQueryVo.setProductId(yxStoreProduct.getId());
            otherStoreList.add(yxSystemStoreQueryVo);
        }
        productDTO.setOtherStoreList(otherStoreList);





        return productDTO;
    }

    /**
     * 商品列表
     *
     * @return
     */
    @Override
    public List<YxStoreProductQueryVo> getGoodsList(YxStoreProductQueryParam productQueryParam) {

        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", CommonEnum.DEL_STATUS_0.getValue()).eq("is_stock_invest", 1).eq("is_invest_on",1).gt("length(image)",0);

        //分类搜索
        if (StrUtil.isNotBlank(productQueryParam.getSid()) && !productQueryParam.getSid().equals("0")) {
           // wrapper.eq("cate_id", productQueryParam.getSid());
            YxStoreCategory yxStoreCategory = yxStoreCategoryService.getById(productQueryParam.getSid());
            List<CateDTO> cateList= yxStoreCategoryService.getAllChilds(yxStoreCategory.getLevelCode());
            List<String> cateIntList = new ArrayList<String>();
            for(CateDTO cateDTO:cateList){
                cateIntList.add(cateDTO.getLevelCode());
            }
            wrapper.in("cate_code",cateIntList);
        }
        //关键字搜索
        if (StrUtil.isNotEmpty(productQueryParam.getKeyword())) {
            wrapper.like("store_name", productQueryParam.getKeyword());
        }

        //




        if (StrUtil.isNotEmpty(productQueryParam.getType())) {
            if (productQueryParam.getType().equals("1")) {
                wrapper.eq("lock_status", 1).eq("is_invested",0);
            }
            else if (productQueryParam.getType().equals("2")) {
                wrapper.eq("is_invested", 1);
            }
            else if (productQueryParam.getType().equals("3")) {
                wrapper.eq("is_invested", 0);
            }
            else if (productQueryParam.getType().equals("4")) {
                wrapper.eq("is_invested", 0).eq("lock_status",0);
            }
            else if (productQueryParam.getType().equals("5")) {
                wrapper.eq("is_hot", 1);
                if (productQueryParam.getSalesOrder().length() ==0 &&productQueryParam.getInvestCostOrder().length() ==0  &&productQueryParam.getPriceOrder().length() ==0 ) {
                    wrapper.orderByAsc("rand()");

                }

            }
        }

        //认购价格区间
        if (productQueryParam.getInvestPriceBegin() != 0 ) {
            wrapper.ge("invest_price",productQueryParam.getInvestPriceBegin());

        }
        if (productQueryParam.getInvestPriceEnd() != 0 ) {
            wrapper.le("invest_price",productQueryParam.getInvestPriceEnd());

        }



        //销量排序
        if (productQueryParam.getSalesOrder().equals("desc")) {
            wrapper.orderByDesc("sales");
        } else if (productQueryParam.getSalesOrder().equals("asc")) {
            wrapper.orderByAsc("sales");
        }
        //认购价排序
        if (productQueryParam.getPriceOrder().equals("desc")) {
            wrapper.orderByDesc("invest_price");
        } else if (productQueryParam.getPriceOrder().equals("asc")) {
            wrapper.orderByAsc("invest_price");
        }
        //认购成本价排序
        if (productQueryParam.getInvestCostOrder().equals("desc")) {
            wrapper.orderByDesc("invest_cost");
        } else if (productQueryParam.getInvestCostOrder().equals("asc")) {
            wrapper.orderByAsc("invest_cost");
        }


   //     wrapper.orderByDesc("add_time");


        Page<YxStoreProduct> pageModel = new Page<>(productQueryParam.getPage(),
                productQueryParam.getLimit());

        IPage<YxStoreProduct> pageList = yxStoreProductMapper.selectPage(pageModel, wrapper);

        List<YxStoreProductQueryVo> list = storeProductMap.toDto(pageList.getRecords());

//        for (GoodsDTO goodsDTO : list) {
//            goodsDTO.setIsCollect(isCollect(goodsDTO.getGoodsId(),userId));
//        }

        return list;
    }

    /**
     * 保留商品列表
     *
     * @param productQueryParam
     * @return
     */
    public List<YxStoreProductQueryVo> getLockProductList(YxStoreProductQueryParam productQueryParam,int uid , List<Integer> saleId) {
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();

        wrapper.eq("is_del", CommonEnum.DEL_STATUS_0.getValue()).eq("is_stock_invest", 1).eq("is_invested", 0).eq("is_invest_on",1).eq("lock_status", 1).orderByAsc("lock_release_time");
        if(uid > 0 &&  saleId == null) wrapper.eq("locker_id",uid);
        else if(saleId != null){
            wrapper.in("locker_id",saleId);
        }

        if (productQueryParam.getLockType() != null && productQueryParam.getLockType() != -1) {
            wrapper.eq("lock_type", productQueryParam.getLockType());
        }
        Page<YxStoreProduct> pageModel = new Page<>(productQueryParam.getPage(),
                productQueryParam.getLimit());
        IPage<YxStoreProduct> pageList = yxStoreProductMapper.selectPage(pageModel, wrapper);

        List<YxStoreProductQueryVo> list = storeProductMap.toDto(pageList.getRecords());
        return list;
    }

    public int getLockProductCount(YxStoreProductQueryParam productQueryParam, int uid){
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", CommonEnum.DEL_STATUS_0.getValue()).eq("is_stock_invest", 1).eq("is_invested", 0).eq("is_invest_on",1).eq("lock_status", 1).eq("locker_id", uid).orderByAsc("lock_release_time");
        return  yxStoreProductMapper.selectCount(wrapper);
    }


    /**
     * 商品列表
     *
     * @param page
     * @param limit
     * @param order
     * @return
     */
    @Override
    public List<YxStoreProductQueryVo> getList(int page, int limit, int order) {

        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0).eq("is_show", 1).orderByDesc("sort");

        // order
        switch (ProductEnum.toType(order)) {
            case TYPE_1:
                wrapper.eq("is_best", 1); //精品推荐
                break;
            case TYPE_3:
                wrapper.eq("is_new", 1); //// 首发新品
                break;
            case TYPE_4:
                wrapper.eq("is_benefit", 1); //// 促销单品
                break;
            case TYPE_2:
                wrapper.eq("is_hot", 1);//// 热门榜单
                break;
        }
        Page<YxStoreProduct> pageModel = new Page<>(page, limit);

        IPage<YxStoreProduct> pageList = yxStoreProductMapper.selectPage(pageModel, wrapper);

        List<YxStoreProductQueryVo> list = storeProductMap.toDto(pageList.getRecords());


        return list;
    }

    @Override
    public YxStoreProductQueryVo getYxStoreProductById(Serializable id) {
        return yxStoreProductMapper.getYxStoreProductById(id);
    }

    @Override
    public YxStoreProductQueryVo getNewStoreProductById(int id) {
        return storeProductMap.toDto(yxStoreProductMapper.selectById(id));
    }

    @Override
    public Paging<YxStoreProductQueryVo> getYxStoreProductPageList(YxStoreProductQueryParam yxStoreProductQueryParam) throws Exception {
        Page page = setPageParam(yxStoreProductQueryParam, OrderItem.desc("create_time"));
        IPage<YxStoreProductQueryVo> iPage = yxStoreProductMapper.getYxStoreProductPageList(page, yxStoreProductQueryParam);
        return new Paging(iPage);
    }

    /**
     * 查询没被投资的商品
     *

     * @return
     */
    @Override
    public List<YxStoreProduct> getListProduct(YxStoreProductQueryParam yxStoreProductQueryParam) {
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0).eq("is_stock_invest", 1).eq("is_invest_on",1);
        if(yxStoreProductQueryParam.getStoreId() != null && !yxStoreProductQueryParam.getStoreId().equals("")){
            wrapper.eq("store_id",yxStoreProductQueryParam.getStoreId());
        }
        Page<YxStoreProduct> pageModel = new Page<>(yxStoreProductQueryParam.getPage(), yxStoreProductQueryParam.getLimit());
        IPage<YxStoreProduct> iPage = yxStoreProductMapper.selectPage(pageModel, wrapper);
        return iPage.getRecords();
    }

    @Override
    public List<YxStoreProduct> getListProductRandom(String storeId,int limit) {
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0).eq("is_stock_invest", 1).eq("is_invest_on",1).eq("lock_status",0).eq("is_invested",0).eq("is_hot",1).ge("length(image)",0).orderByAsc("rand()");
        if(storeId != null && !storeId.equals("")){
            wrapper.eq("store_id",storeId);
        }
        Page<YxStoreProduct> pageModel = new Page<>(1, limit);
        IPage<YxStoreProduct> iPage = yxStoreProductMapper.selectPage(pageModel, wrapper);

        return iPage.getRecords();
    }

    @Override
    public List<YxStoreProduct> saleRanking(YxStoreProductQueryParam yxStoreProductQueryParam){
        QueryWrapper<YxStoreProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", CommonEnum.DEL_STATUS_0.getValue()).eq("is_stock_invest", 1).eq("is_invested", 0).eq("is_invest_on",1).gt("length(image)",0).orderByDesc("rand()");
        Page<YxStoreProduct> pageModel = new Page<>(yxStoreProductQueryParam.getPage(), yxStoreProductQueryParam.getLimit());
        IPage<YxStoreProduct> iPage = yxStoreProductMapper.selectPage(pageModel, wrapper);

        return iPage.getRecords();
    }


    /**
     * 根据条码查询商品
     * @param barCode
     * @return
     */
    @Override
    public YxStoreProductQueryVo findByBarCodeGoogs(String barCode) {
        return yxStoreProductMapper.findByBarCodeGoogs(barCode);
    }

}
